package org.atf.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringReader;
import java.net.URL;
//import java.nio.file.Files;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Properties;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.servlet.http.HttpSession;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.io.FileUtils;
import org.apache.commons.mail.DefaultAuthenticator;
import org.apache.commons.mail.Email;
import org.apache.commons.mail.EmailException;
import org.apache.commons.mail.SimpleEmail;
import org.apache.directory.api.ldap.model.exception.LdapException;
import org.apache.directory.ldap.client.api.LdapConnection;
import org.apache.directory.ldap.client.api.LdapNetworkConnection;
import org.apache.log4j.Logger;
import org.atf.command.AtfLocal;
import org.atf.command.AtfRemote;
import org.atf.model.dao.AuditDAO;
import org.atf.model.dao.LdapConfigDAO;
import org.atf.model.dao.PreferenceDAO;
import org.atf.model.dao.ProfileDAO;
import org.atf.model.dao.ServerDAO;
import org.atf.model.dao.UserDAO;
import org.atf.model.entity.Audit;
import org.atf.model.entity.LdapConfig;
import org.atf.model.entity.Preference;
import org.atf.model.entity.Profile;
import org.atf.model.entity.User;
import org.directwebremoting.WebContext;
import org.directwebremoting.WebContextFactory;
import org.jasypt.util.text.BasicTextEncryptor;

import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.SftpException;

public class ATFUtils {
	public static String  APP_USERNAME_HEADER="ATF_USER";
	public static String  APP_GROUPS_HEADER="ATF_GROUPS";
	public static String encryptionPassword="hibernateStringEncryptor123454*";
	public static String ATF_USER_PASSWORD="admin4Not3";

	private  static Logger  logger = Logger.getLogger(ATFUtils.class);
	public static String getResourcePath(String fileName){
		String directoryPath=System.getProperty("com.atf.config.path");
		
		String filePath="";
		if(directoryPath != null){
			logger.info("Found com.atf.config.path: "+directoryPath);
			filePath=directoryPath+'/'+fileName;
		}else{
			logger.info("Searching the classpath: ");
			URL url=Thread.currentThread().getContextClassLoader().getResource(fileName);
			if(url != null){
				filePath=url.getPath();
			}
			
		}
		logger.info("fileName Path: "+filePath);
		return filePath;
	}
	public static String getAppUserHeader(){
		logger.debug("getAppUserHeader");
		PreferenceDAO preferenceDAO= new PreferenceDAO();
		String app_user_header=ATFUtils.APP_USERNAME_HEADER;
		Preference userHeaderPref=preferenceDAO.getPreferenceByNameScope("APP_USERNAME_HEADER", "GLOBAL");
		if( userHeaderPref != null){
			if(userHeaderPref.getpValue() != null && !userHeaderPref.getpValue().equalsIgnoreCase("")){
				app_user_header=userHeaderPref.getpValue();
				logger.debug("Found APP_USERNAME_HEADER : Scope GLOBAL");
			}
		}
		logger.debug("User Header value: "+app_user_header);
		return app_user_header;
	}
	public static String getAppGroupsHeader(){
		PreferenceDAO preferenceDAO= new PreferenceDAO();
		String app_group_header=ATFUtils.APP_GROUPS_HEADER;

		Preference groupHeaderPref=preferenceDAO.getPreferenceByNameScope("APP_GROUPS_HEADER", "GLOBAL");
		if( groupHeaderPref != null){
			if(groupHeaderPref.getpValue() != null && !groupHeaderPref.getpValue().equalsIgnoreCase("")){
				app_group_header=groupHeaderPref.getpValue();
				logger.debug("Found APP_GROUPS_HEADER : Scope GLOBAL");
			}
		}
		logger.debug("Group Header value: "+app_group_header);
		return app_group_header;
	}
	
	public static String getDeployParameters(HashMap<String, String> arguments) {
		// TODO Auto-generated method stub
		String result="";
		logger.debug("arguments :"+arguments);
		if(arguments != null){
			if(arguments.containsKey("emailTo")){
				if(!arguments.get("emailTo").equalsIgnoreCase("")){
					result+=" -s "+arguments.get("emailTo");
				}
			}
			if(arguments.containsKey("deployFiles")){
				if(!arguments.get("deployFiles").equalsIgnoreCase("")){
					result+=" -e "+arguments.get("deployFiles");
				}
			}
			if(arguments.containsKey("autoRestartEnabled")){
				if(arguments.get("autoRestartEnabled").equalsIgnoreCase("true")){
					result+=" -r true";
				}
			}
			if(arguments.containsKey("clearCacheEnabled")){
				if(arguments.get("clearCacheEnabled").equalsIgnoreCase("true")){
					result+=" -c true";
				}
			}
			
		}
		logger.info(result);
		return result;
	}
	
	public static boolean isTamEnabled(){
		PreferenceDAO preferenceDAO= new PreferenceDAO();
		Preference tamEnabled=preferenceDAO.getPreferenceByNameScope("TAM_ENABLED", "GLOBAL");
		if( tamEnabled != null){
			if(tamEnabled.getpValue() != null && !tamEnabled.getpValue().equalsIgnoreCase("")){
				if( tamEnabled.getpValue().equalsIgnoreCase("true")){
					return true;
				}
			}
		}
		return false;
	}
	
	public static User buildTamUser(String username, String groupsStr){
		User user= new User();
		user.setUsername(username);
		user.setGroups(groupsStr);
		user.setAdmin(String.valueOf(isAdmin(groupsStr)));
		return user;
	}
	
	public static boolean isAdmin(String groupStr){
		logger.debug(groupStr);
		PreferenceDAO preferenceDAO= new PreferenceDAO();
		Preference adminGroups=preferenceDAO.getPreferenceByNameScope("ADMIN_GROUPS", "GLOBAL");
		if(adminGroups !=null && groupStr != null && !groupStr.equalsIgnoreCase("")){
			String gStr=groupStr.replaceAll("\"", "");
			if(gStr != null && !gStr.equalsIgnoreCase("")){
				String value=adminGroups.getpValue();
				if(value != null && !value.equalsIgnoreCase("")){
					String[] temp = value.split(",");
					for(String ad:temp){
						int index1=gStr.indexOf(ad);
						if (index1 != -1){
							logger.info("Admin Enabled ");
							return true;
						}
					}
				}
			}
		}else{
			logger.info("Admin not Enabled");
		}
		return false;
	}
	public static boolean isTestMode(){
		PreferenceDAO preferenceDAO= new PreferenceDAO();
		Preference testMode=preferenceDAO.getPreferenceByNameScope("TEST_MODE_ENABLE", "GLOBAL");
		if(testMode != null){
			if(testMode.getpValue() != null && testMode.getpValue().equalsIgnoreCase("true")){
				logger.info("Test Mode Enabled");
				return true;
			}
		}
		
		return false;
	}
	
	public static User getATFAdminRoot(String username, String password){
		User user= null;	
		logger.info("admin Authenticating...."+username+ " Password: *******");
		PreferenceDAO preferenceDAO= new PreferenceDAO();
		boolean disableAdmin=false;
		Preference disableAdminPref=preferenceDAO.getPreferenceByNameScope("DISABLE_ADMIN_ACCOUNT", "GLOBAL");
		if(disableAdminPref != null){
			if(disableAdminPref.getpValue() != null && disableAdminPref.getpValue().equalsIgnoreCase("true")){
				logger.info("DISABLE_ADMIN_ACCOUNT");
				disableAdmin=true;
			}
		}
		
		if(!disableAdmin){
			if(username.equals("ATFadmin") && password.equals(ATF_USER_PASSWORD)){
				user=new  User(username,"true","");
			}
		}
		
		return user;
	}
	public static User isUserAuthenticated(String username , String password){
		
		logger.info("User Authenticating...."+username+ " Password: *******");
		LdapConfigDAO ldapConfigDAO= new LdapConfigDAO ();
		List<LdapConfig> ldpapList=ldapConfigDAO.getAllLdapConfig();
		LdapConfig ldapConfig= null;
		if(ldpapList.size() > 0){
			ldapConfig=ldpapList.get(0);
		}
		PreferenceDAO preferenceDAO= new PreferenceDAO();
		UserDAO userDAO= new UserDAO();
		boolean enabledLdap=false;
		Preference enabledLdapPref=preferenceDAO.getPreferenceByNameScope("ENABLE_LDAP", "GLOBAL");
		if(enabledLdapPref != null){
			if(enabledLdapPref.getpValue() != null && enabledLdapPref.getpValue().equalsIgnoreCase("true")){
				logger.info("enabled Ldap Mode Enabled");
				enabledLdap=true;
			}
		}
		User user= null;
		if(ldapConfig != null &&  enabledLdap){
			// get the ldap connection and authenticated
			logger.debug("LdapConifguration Found....");
			LdapConnection connection = new LdapNetworkConnection( ldapConfig.getLdapHostname(), ldapConfig.getLdapPort() );
			String userId="";
			if(ldapConfig.getLdapUserDn() != null && !ldapConfig.getLdapUserDn().equalsIgnoreCase("")){
				userId+=ldapConfig.getLdapUserDn()+username;
			}
			
			if( ldapConfig.getLdapBaseDn() != null && !ldapConfig.getLdapBaseDn().equalsIgnoreCase("")){
				userId+=","+ldapConfig.getLdapBaseDn();
			}
			logger.debug("User DN: "+userId);
			try {
				
				connection.bind(userId, password);
				if(connection.isAuthenticated()){
					logger.info("Success: "+username);
					logger.debug("Getting User object");
					user=userDAO.getUserByName(username);
					if(user == null){
						user=new  User(username,"","");
						Preference userAddPref=preferenceDAO.getPreferenceByNameScope("USER_ADD_AFTER_LOGIN", "GLOBAL");
						if(userAddPref != null){
							if(userAddPref.getpValue() != null && userAddPref.getpValue().equalsIgnoreCase("true")){
								logger.info("Adding the logged in user: "+username);
								userDAO.insertUser(user);
							}
						}
					}
				}
			} catch (LdapException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				user = null;
			}
		}else{
			logger.debug("Getting User object from local repository");
			user=userDAO.getUserByName(username);
			if(user != null){
				if (!user.getPassword().equals(password)){
					user= null;
				}
			}
		}
		if( user != null){
			logger.debug("Found the user");
			return user;
		}
		
		return null;
	}
	
	public static String getUserGroups(String username){
		return "";
	}
	
	public static String getApplicationName(String serverName){
		String sName= serverName;
		String suffix  = null;
		String prefix = null;
		PreferenceDAO preferenceDAO= new PreferenceDAO();
		Preference suffixPref=preferenceDAO.getPreferenceByNameScope("APP_SERVER_SUFFIX","GLOBAL");
		if(suffixPref != null){
			suffix=suffixPref.getpValue();
			logger.debug("APP_SERVER_SUFFIX : "+suffix);
		}
		Preference prefixPref=preferenceDAO.getPreferenceByNameScope("APP_SERVER_PREFIX","GLOBAL");
		if(prefixPref != null){
			
			prefix=prefixPref.getpValue();
			logger.debug("APP_SERVER_PREFIX : "+prefix);
		}
		
		if(suffix != null && !suffix.equalsIgnoreCase("")){
			sName=sName.replaceAll(suffix+"$", "");
			
		}
		if(prefix != null && !prefix.equalsIgnoreCase("")){
			
			sName= sName.replaceAll("^"+prefix,"");
		}
		logger.debug("ServerName "+serverName);
		logger.debug("sName "+sName);
		return sName;
	}
	public static List<String> parseAtfGroups(String groupStr) {
		// TODO Auto-generated method stub
		logger.debug(groupStr);
		List<String> groupsList=new ArrayList<String>();
		if(groupStr != null && !groupStr.equalsIgnoreCase("")){
			String gStr=groupStr.replaceAll("\"", "");
			String[] temp;
			String delimeter = ",";
			temp = gStr.split(delimeter);  
			PreferenceDAO preferenceDAO= new PreferenceDAO();
			Preference patternStr=preferenceDAO.getPreferenceByNameScope("APP_GROUPS_PARSE_PATTERN", "GLOBAL");
			String groupPatternStr="restart_(.*)";
			if(patternStr != null && !patternStr.getpValue().equalsIgnoreCase("")){
				groupPatternStr=patternStr.getpValue();
				Pattern pattern = Pattern.compile(groupPatternStr,Pattern.CASE_INSENSITIVE);
				for(int i =0; i < temp.length ; i++){
					logger.debug("group : "+temp[i]);
					Matcher matcher = pattern.matcher(temp[i]);
					if(matcher.matches()){
						groupsList.add((temp[i]));
					}
					
				}
				
			}else{
				for(int i =0; i < temp.length ; i++){
					logger.debug("group : "+temp[i]);
					groupsList.add((temp[i]));
				}
			}
			
			
			
			
		}
		logger.debug("groups List:"+groupsList.toString());
		return groupsList;
	}
	
	public static String parseDeployFile(String responseFile){
		
		if(responseFile.endsWith("_RESP.txt")){
			String[] temp;
			temp=responseFile.split("_RESP");
			if(temp.length >1){
				return temp[0];
			}
		}
		return ""; 
	}
	
	
	public static boolean matchAppServerName(String serverName, List<String> groups) {
		// TODO Auto-generated method stub

		String appName= getApplicationName(serverName);
		logger.debug("sName "+appName);
		for(String ad:groups){
			logger.debug("group : "+ad);
			if (appName.matches(ad)){
				logger.debug("Group: "+ad+" Matches a Server  Name: "+appName);
				return true;
			}
				
//			int index1=ad.indexOf(appName);
//			logger.debug("match index : "+index1);
//			if (index1 != -1){
//				logger.info("match index : true");
//				return true;
//			}
		}
		return false;
	}
	
	public static AtfRemote getAtfRemote(Integer profileId){
		logger.info("Getting the Remote Object");
		String sshUsername= "";
		String sshPassword="";
		int sshPort =22;
		String sshKnownHostFile="";
		ProfileDAO profileDAO= new ProfileDAO();
		PreferenceDAO preferenceDAO= new PreferenceDAO();
		String profileHostname=profileDAO.getProfileHostname(profileId);
		Preference sshUsernamePref= preferenceDAO.getPreferenceByName(profileId, 0, "SSH_USERNAME", "PROFILE");
		if(sshUsernamePref != null){
			sshUsername=sshUsernamePref.getpValue();
		}
		logger.debug("SSH username: "+sshUsername);
		Preference sshPasswordPref= preferenceDAO.getPreferenceByName(profileId, 0, "SSH_PASSWORD", "PROFILE");
		if(sshPasswordPref != null){
			sshPassword=sshPasswordPref.getpValue();
			//if(ATFUtils.isEncoded(sshPassword)){
			sshPassword=ATFUtils.decode(sshPassword);
			//}
		}
		logger.debug("SSH Password: *********");
		Preference sshPortPref= preferenceDAO.getPreferenceByName(profileId, 0, "SSH_PORT", "PROFILE");
		if(sshPortPref != null){
			sshPort=Integer.parseInt(sshPortPref.getpValue());
		}
		logger.debug("SSH Port: "+sshPort);
		Preference sshKnownHostFilePref= preferenceDAO.getPreferenceByName(profileId, 0, "SSH_KNOWN_HOST_FILE", "PROFILE");
		if(sshKnownHostFilePref != null){
			sshKnownHostFile=sshKnownHostFilePref.getpValue();
			
		}
		logger.debug("SSH sshKnownHostFile: "+sshKnownHostFile);
		logger.info("hostname: "+profileHostname+" sshUsername: "+sshUsername+" sshPort"+sshPort);
		AtfRemote atfRemote= new AtfRemote(profileHostname,sshUsername,sshPassword,sshPort,sshKnownHostFile);
		return atfRemote;
	}
	public static String uploadWasConfigFile(Integer profileId,
			String serverName, String configData) {
		// TODO Auto-generated method stub
		logger.info("Getting the configuration File");
		PreferenceDAO preferenceDAO= new PreferenceDAO();
		ProfileDAO profileDAO= new ProfileDAO();
		boolean sshEnabled= false;
		Preference sshEnabledPref=preferenceDAO.getPreferenceByName(profileId, 0, "SSH_ENABLED", "PROFILE");
		
		if(sshEnabledPref != null){
			sshEnabled =Boolean.parseBoolean(sshEnabledPref.getpValue());
			logger.info("sshEnabled: "+sshEnabled);
		}
		String appName= getApplicationName(serverName);
		logger.info("appName: "+appName);
		String responseFile="";
		String scriptPath="";
		Preference scriptPathPrf= preferenceDAO.getPreferenceByName(profileId, 0, "SCRIPT_PATH", "PROFILE");
		if(scriptPathPrf != null){
			scriptPath=scriptPathPrf.getpValue();
		}
		if( !scriptPath.equalsIgnoreCase("")){
			responseFile=scriptPath+"/responsefiles/config/"+appName+"/"+appName+"_RESP.txt";
		}else{
			responseFile="/apps/scripts/v70/responsefiles/config/"+appName+"/"+appName+"_RESP.txt";
		}
		logger.info("responseFile: "+responseFile);		
		String tempDir="/tmp";
		Preference tempDirPref= preferenceDAO.getPreferenceByName("TEMP_DIR");
		if(tempDirPref != null){
			tempDir=tempDirPref.getpValue();
		}
		Properties configFile = new Properties();
		String result= "ERROR: Unknown";
		try {
			
			File file = new File(tempDir+"/"+appName+"_RESP.txt");
			FileOutputStream fileOut = new FileOutputStream(file);
			configFile.store(fileOut,configData);
			fileOut.close();
			if(file.exists()){
				if( sshEnabled){
					AtfRemote atfRemote= getAtfRemote(profileId);
					try {
						atfRemote.put(tempDir+"/"+appName+"_RESP.txt", responseFile);
						result="SUCCESS: Upload Success";
					} catch (JSchException e) {
						// TODO Auto-generated catch block
						
						result="ERROR:"+e.getMessage();
					} catch (SftpException e) {
						// TODO Auto-generated catch block
						result="ERROR:"+e.getMessage();
					}
				}else{
					File Localfile = new File(responseFile);
					AtfLocal atfLocal= new AtfLocal();
					atfLocal.copy(file, Localfile);
					result="SUCCESS: Upload Success";
				}
			}
			
		} catch (IOException e) {
			// TODO Auto-generated catch block
			
			result= "ERROR: "+e.getMessage();
		}
		
		return result;

	}
	
	public static List<String> getDeployFilesList(Integer profileId, String serverName){
		logger.info("Getting the Deployment File");
		List<String> result= new ArrayList<String>();
		PreferenceDAO preferenceDAO= new PreferenceDAO();
		ProfileDAO profileDAO= new ProfileDAO();
		boolean sshEnabled= false;
		Preference sshEnabledPref=preferenceDAO.getPreferenceByName(profileId, 0, "SSH_ENABLED", "PROFILE");
		
		if(sshEnabledPref != null){
			sshEnabled =Boolean.parseBoolean(sshEnabledPref.getpValue());
			logger.info("sshEnabled: "+sshEnabled);
		}
		String appName= getApplicationName(serverName);
		logger.info("appName: "+appName);
		String responseFilePath="";
		String scriptPath="";
		Preference scriptPathPrf= preferenceDAO.getPreferenceByName(profileId, 0, "SCRIPT_PATH", "PROFILE");
		if(scriptPathPrf != null){
			scriptPath=scriptPathPrf.getpValue();
		}
		if( !scriptPath.equalsIgnoreCase("")){
			responseFilePath=scriptPath+"/responsefiles/deploy/"+appName;
		}else{
			responseFilePath="/apps/scripts/v70/responsefiles/deploy/"+appName;
		}
		logger.info("responseFile: "+responseFilePath);		
		if( sshEnabled){
			logger.info("Loading from Remote file: ");	
			AtfRemote atfRemote= getAtfRemote(profileId);
			 try {
				 List<String> filesList =atfRemote.getFileList(responseFilePath+"/*_RESP.txt");
				 for (int i = 0; i < filesList.size(); i++){
					 String fileN=filesList.get(i);
					 fileN= parseDeployFile(fileN);
					 if(!fileN.equalsIgnoreCase("")){
						 result.add(fileN);
					 }
				 }
					 
			} catch (JSchException e) {
				// TODO Auto-generated catch block
				logger.error(e.getMessage());
			} catch (SftpException e) {
				// TODO Auto-generated catch block
				logger.error(e.getMessage());
			}
			
		}else{
			logger.info("Loading from Local file: "+responseFilePath);	
			File folder = new File(responseFilePath);
			File[] listOfFiles = folder.listFiles();
			String files;
			for (int i = 0; i < listOfFiles.length; i++) 
			  {
				if (listOfFiles[i].isFile()){
					files = listOfFiles[i].getName();
					if (files.endsWith("_RESP.txt")){
						files= parseDeployFile(files);
						 if(!files.equalsIgnoreCase("")){
							 result.add(files);
						 }
					}
				}
					
			  }
		}
		return result;
		
	}
	public static String getWasConfigFilePath(Integer profileId,
			String serverName) {
		// TODO Auto-generated method stub
		logger.info("Getting the configuration File");
		String appName= getApplicationName(serverName);
		logger.info("appName: "+appName);
		PreferenceDAO preferenceDAO= new PreferenceDAO();
		String tempDir="/tmp";
		Preference tempDirPref= preferenceDAO.getPreferenceByName("TEMP_DIR");
		if(tempDirPref != null){
			tempDir=tempDirPref.getpValue();
		}
		
		boolean sshEnabled= false;
		Preference sshEnabledPref=preferenceDAO.getPreferenceByName(profileId, 0, "SSH_ENABLED", "PROFILE");
		
		if(sshEnabledPref != null){
			sshEnabled =Boolean.parseBoolean(sshEnabledPref.getpValue());
			logger.info("sshEnabled: "+sshEnabled);
		}
		String scriptPath="";
		String responseFile="";
		Preference scriptPathPrf= preferenceDAO.getPreferenceByName(profileId, 0, "SCRIPT_PATH", "PROFILE");
		if(scriptPathPrf != null){
			scriptPath=scriptPathPrf.getpValue();
		}
		if( !scriptPath.equalsIgnoreCase("")){
			responseFile=scriptPath+"/responsefiles/config/"+appName+"/"+appName+"_RESP.txt";
		}else{
			responseFile="/apps/scripts/v70/responsefiles/config/"+appName+"/"+appName+"_RESP.txt";
		}
		logger.info("responseFile: "+responseFile);	
		
		String fileName="";
		if( sshEnabled){
			fileName=tempDir+"/"+appName+"_RESP.txt";
		}else{
			fileName=responseFile;
		}
		
		return fileName;
	}
	public static String getWasConfig(Integer profileId, String serverName){
		logger.info("Getting the configuration File");
		String result= "";
		PreferenceDAO preferenceDAO= new PreferenceDAO();
		ProfileDAO profileDAO= new ProfileDAO();
		boolean sshEnabled= false;
		Preference sshEnabledPref=preferenceDAO.getPreferenceByName(profileId, 0, "SSH_ENABLED", "PROFILE");
		
		if(sshEnabledPref != null){
			sshEnabled =Boolean.parseBoolean(sshEnabledPref.getpValue());
			logger.info("sshEnabled: "+sshEnabled);
		}
		String appName= getApplicationName(serverName);
		logger.info("appName: "+appName);
		String responseFile="";
		String scriptPath="";
		Preference scriptPathPrf= preferenceDAO.getPreferenceByName(profileId, 0, "SCRIPT_PATH", "PROFILE");
		if(scriptPathPrf != null){
			scriptPath=scriptPathPrf.getpValue();
		}
		if( !scriptPath.equalsIgnoreCase("")){
			responseFile=scriptPath+"/responsefiles/config/"+appName+"/"+appName+"_RESP.txt";
		}else{
			responseFile="/apps/scripts/v70/responsefiles/config/"+appName+"/"+appName+"_RESP.txt";
		}
		logger.info("responseFile: "+responseFile);		
		String tempDir="/tmp";
		Preference tempDirPref= preferenceDAO.getPreferenceByName("TEMP_DIR");
		if(tempDirPref != null){
			tempDir=tempDirPref.getpValue();
		}
		
		logger.info("tempDir: "+tempDir);
		if( sshEnabled){
			
			AtfRemote atfRemote= getAtfRemote(profileId);
			try {
				File localFile=atfRemote.getFile(responseFile, tempDir+"/"+appName+"_RESP.txt");
				if( localFile != null){
					
					if (localFile.exists()){
						logger.info("File Exists: "+tempDir+"/"+appName+"_RESP.txt");
						result = FileUtils.readFileToString(localFile);
						logger.info("Loaded: OK");	
					}
				}
				
		 	} catch (JSchException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (SftpException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (FileNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
		}else{
			logger.info("Loading from Local file: "+responseFile);	
			try {
				
				File localFile=new File(responseFile);
				if(localFile.exists()){
					
					logger.info("Loading from Local file: OK");
					result = FileUtils.readFileToString(localFile);
					logger.info("Loaded: OK");	
				}
				
	            
	        } catch (FileNotFoundException e) {
	            e.printStackTrace();
	        } catch (IOException e) {
	            e.printStackTrace();
	        }
		}
		return result;
	}
	public static Properties getWasConfigProperty(Integer profileId, String serverName){
		logger.info("Getting the configuration File");
		Properties configProperty= null;
		PreferenceDAO preferenceDAO= new PreferenceDAO();
		ProfileDAO profileDAO= new ProfileDAO();
		boolean sshEnabled= false;
		Preference sshEnabledPref=preferenceDAO.getPreferenceByName(profileId, 0, "SSH_ENABLED", "PROFILE");
		
		if(sshEnabledPref != null){
			sshEnabled =Boolean.parseBoolean(sshEnabledPref.getpValue());
			logger.info("sshEnabled: "+sshEnabled);
		}
		String appName= getApplicationName(serverName);
		logger.info("appName: "+appName);
		String responseFile="";
		String scriptPath="";
		Preference scriptPathPrf= preferenceDAO.getPreferenceByName(profileId, 0, "SCRIPT_PATH", "PROFILE");
		if(scriptPathPrf != null){
			scriptPath=scriptPathPrf.getpValue();
		}
		if( !scriptPath.equalsIgnoreCase("")){
			responseFile=scriptPath+"/responsefiles/config/"+appName+"/"+appName+"_RESP.txt";
		}else{
			responseFile="/apps/scripts/v70/responsefiles/config/"+appName+"/"+appName+"_RESP.txt";
		}
		logger.info("responseFile: "+responseFile);		
		String tempDir="/tmp";
		Preference tempDirPref= preferenceDAO.getPreferenceByName("TEMP_DIR");
		if(tempDirPref != null){
			tempDir=tempDirPref.getpValue();
		}
		
		logger.info("tempDir: "+tempDir);
		if( sshEnabled){
			
			AtfRemote atfRemote= getAtfRemote(profileId);
			try {
				File localFile=atfRemote.getFile(responseFile, tempDir+"/"+appName+"_RESP.txt");
				if( localFile != null){
					
					if (localFile.exists()){
						logger.info("File Exists: "+tempDir+"/"+appName+"_RESP.txt");
						configProperty = new Properties();
						InputStream is = new FileInputStream(localFile);
						logger.info("Loadding: "+tempDir+"/"+appName+"_RESP.txt");
						configProperty.load(is);
						logger.info("Loaded: OK");	
					}
				}
				
			} catch (JSchException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (SftpException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (FileNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
		}else{
			logger.info("Loading from Local file: "+responseFile);	
			try {
				configProperty = new Properties();
				File localFile=new File(responseFile);
				if(localFile.exists()){
					InputStream is = new FileInputStream(localFile);
					configProperty.load(is);
					logger.info("Loading from Local file: OK");
				}
				
	            
	        } catch (FileNotFoundException e) {
	            e.printStackTrace();
	        } catch (IOException e) {
	            e.printStackTrace();
	        }
		}
		logger.trace("configProperty: "+configProperty.toString());	
		return configProperty;
	}
	
	public static String encode(String password){
		BasicTextEncryptor textEncryptor = new BasicTextEncryptor();
		textEncryptor.setPassword(encryptionPassword);
		String myEncryptedText = textEncryptor.encrypt(password);
		return myEncryptedText;
	}
	public static String decode(String password){
		BasicTextEncryptor textEncryptor = new BasicTextEncryptor();
		textEncryptor.setPassword(encryptionPassword);
		String plainText = textEncryptor.decrypt(password);
		return  plainText;
	}
	
	public static boolean isEncoded(String password){
		Byte bObj1 = new Byte(password);
		return false;
	}
	public static boolean sendTextEmail(String toAddress, String fromAddress, String subject, String message){
		if(message != null && !message.equalsIgnoreCase("")){
			//String toAddress= System.getProperty("Email.ToAddress");
			//String ccAddress= System.getProperty("Email.CcAddress");
			//String FromAddress= System.getProperty("Email.FromAddress");
			//String hostName= System.getProperty("Email.Host");
			//String sendEmail= System.getProperty("Email.SendEmail");
			//String subject= System.getProperty("Email.Subject");
			PreferenceDAO preferenceDAO= new PreferenceDAO();
			
			boolean smtpEnabled= false;
			String smtpHostname="";
			String smtpPort="";
			Preference smtpEnabledPref=preferenceDAO.getPreferenceByName("SMTP_ENABLED");
			if(smtpEnabledPref != null){
				String smtpEnabledValue=smtpEnabledPref.getpValue();
				if(smtpEnabledValue != null && smtpEnabledValue.equalsIgnoreCase("true")){
					smtpEnabled= true;
				}
			}
			Preference smtpHostPref=preferenceDAO.getPreferenceByName("SMTP_HOSTNAME");
			if(smtpHostPref != null){
				String smtpHostPrefValue=smtpHostPref.getpValue();
				if(smtpHostPrefValue != null && !smtpHostPrefValue.equalsIgnoreCase("")){
					smtpHostname=smtpHostPrefValue;
				}
			}
			Preference smtpPortPref=preferenceDAO.getPreferenceByName("SMTP_PORT");
			if(smtpPortPref != null){
				String smtpPortPrefValue=smtpPortPref.getpValue();
				if(smtpPortPrefValue != null && !smtpPortPrefValue.equalsIgnoreCase("")){
					smtpPort=smtpPortPrefValue;
				}
			}
			
			logger.debug("SMTP_ENABLED ...."+smtpEnabled);	
			logger.debug("SMTP_HOSTNAME ...."+smtpHostname);	
			
			if(smtpEnabled){
				if ( toAddress != null && smtpHostname != null && fromAddress != null ){
					if (!toAddress.equalsIgnoreCase("") && !smtpHostname.equalsIgnoreCase("") && !fromAddress.equalsIgnoreCase("")){
						System.out.println("sending the email");
						Properties properties = System.getProperties();
						properties.setProperty("mail.transport.protocol", "smtp");
						properties.setProperty("mail.smtp.host", smtpHostname);
						Session session = Session.getDefaultInstance(properties, null);
						session.setDebug(false);

						try{
							Transport transport = session.getTransport();
						 // Create a default MimeMessage object.
						 MimeMessage messageSession = new MimeMessage(session);

						 // Set From: header field of the header.
						 messageSession.setFrom(new InternetAddress(fromAddress));

						 // Set To: header field of the header.
						 messageSession.addRecipient(Message.RecipientType.TO,new InternetAddress(toAddress));
//						 if (ccAddress !=null && !ccAddress.equalsIgnoreCase("")){
//							 messageSession.addRecipient(Message.RecipientType.CC,new InternetAddress(ccAddress));
//						 }


						 // Set Subject: header field
						 if (subject == null ){
							 messageSession.setSubject("AFT TOOL Email System");
						 }else{
							 messageSession.setSubject(subject);
						 }


						 // Now set the actual message
						 messageSession.setText(message);

						 // Send message
						 transport.connect();
						 transport.sendMessage(messageSession, messageSession.getRecipients(Message.RecipientType.TO));
						 transport.close();
						 logger.debug("Sent message successfully....");
						 return true;
					      }catch (MessagingException mex) {
						 mex.printStackTrace();
					      }

					}
				}
			}
		}
		return false;
	}

	
	public static boolean sendTextEmail1(String toAddress, String fromAddress, String subject, String message){
		logger.debug("Sending Text Email ....");	
		PreferenceDAO preferenceDAO= new PreferenceDAO();
		
		boolean smtpEnabled= false;
		String smtpHostname="";
		String smtpPort="";
		Preference smtpEnabledPref=preferenceDAO.getPreferenceByName("SMTP_ENABLED");
		if(smtpEnabledPref != null){
			String smtpEnabledValue=smtpEnabledPref.getpValue();
			if(smtpEnabledValue != null && smtpEnabledValue.equalsIgnoreCase("true")){
				smtpEnabled= true;
			}
		}
		Preference smtpHostPref=preferenceDAO.getPreferenceByName("SMTP_HOSTNAME");
		if(smtpHostPref != null){
			String smtpHostPrefValue=smtpHostPref.getpValue();
			if(smtpHostPrefValue != null && !smtpHostPrefValue.equalsIgnoreCase("")){
				smtpHostname=smtpHostPrefValue;
			}
		}
		Preference smtpPortPref=preferenceDAO.getPreferenceByName("SMTP_PORT");
		if(smtpPortPref != null){
			String smtpPortPrefValue=smtpPortPref.getpValue();
			if(smtpPortPrefValue != null && !smtpPortPrefValue.equalsIgnoreCase("")){
				smtpPort=smtpPortPrefValue;
			}
		}
		
		logger.debug("SMTP_ENABLED ...."+smtpEnabled);	
		logger.debug("SMTP_HOSTNAME ...."+smtpHostname);	
		if(smtpEnabled){
			if(!smtpHostname.equalsIgnoreCase("")){
				Email email = new SimpleEmail();
				email.setHostName(smtpHostname);
				if(!smtpPort.equalsIgnoreCase("")){
					email.setSmtpPort(465);
				}
				boolean smtpAuthEnabled= false;
				Preference smtpAuthEnabledPref=preferenceDAO.getPreferenceByName("SMTP_AUTH_ENABLED");
				if(smtpAuthEnabledPref != null){
					if(smtpAuthEnabledPref.getpValue() != null && smtpAuthEnabledPref.getpValue().equalsIgnoreCase("true")){
						smtpAuthEnabled=true;
					}
				}
				
				if( smtpAuthEnabled){
					String username="";
					String password="";
					Preference smtpAuthUsernamePref=preferenceDAO.getPreferenceByName("SMTP_AUTH_USERNAME");
					if(smtpAuthUsernamePref != null){
						if(smtpAuthUsernamePref.getpValue() != null && !smtpAuthUsernamePref.getpValue().equalsIgnoreCase("")){
							username=smtpAuthUsernamePref.getpValue();
						}
					}
					Preference smtpAuthPasswordPref=preferenceDAO.getPreferenceByName("SMTP_AUTH_PASSWORD");
					if(smtpAuthPasswordPref != null){
						if(smtpAuthPasswordPref.getpValue() != null && !smtpAuthPasswordPref.getpValue().equalsIgnoreCase("")){
							password=ATFUtils.decode(smtpAuthPasswordPref.getpValue());
						}
					}
					
					if(!username.equalsIgnoreCase("") && password.equalsIgnoreCase("")){
						email.setAuthenticator(new DefaultAuthenticator(username, password));
					}
				}
			
				if(fromAddress == null || fromAddress.equalsIgnoreCase("")){
					Preference smtpFromAddressPref=preferenceDAO.getPreferenceByName("SMTP_FROM_ADDRESS");
					if(smtpFromAddressPref != null){
						if(smtpFromAddressPref.getpValue() != null && !smtpFromAddressPref.getpValue().equalsIgnoreCase("")){
							fromAddress=smtpFromAddressPref.getpValue();
						}
					}
				}
				if(toAddress == null || toAddress.equalsIgnoreCase("")){
					Preference smtpToAddressPref=preferenceDAO.getPreferenceByName("SMTP_TO_ADDRESS");
					if(smtpToAddressPref != null){
						if(smtpToAddressPref.getpValue() != null && !smtpToAddressPref.getpValue().equalsIgnoreCase("")){
							toAddress=smtpToAddressPref.getpValue();
						}
					}
				}
				logger.debug("To: "+toAddress+" From:"+fromAddress);	
				
				try {
					email.setFrom(fromAddress);
					email.addTo(toAddress);
					email.setSubject(subject);
					email.setMsg(message);
					email.send();
					return true;
				} catch (EmailException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}else{
			
		}
		return false;
	}

	public static String getSessionUsername(){
		
		WebContext ctx = WebContextFactory.get();
		HttpSession session=ctx.getSession();
		User user =(User) session.getAttribute("ATFUser");
		if( user != null){
			return user.getUsername();
		}else{
			return "";
		}
	}
	public static void addUserLoginAudit(User user){
		AuditDAO auditDAO= new AuditDAO();
		logger.info("User logged: "+user.getUsername());	
		Calendar sCal= Calendar.getInstance();
		auditDAO.insertAudit(new Audit(user.getUsername(),0,
				"LOGIN",sCal.getTime(), sCal.getTime(),"LOGGED: "+user.getUsername()));
	}
	public static void addUserLogoutAudit(User user){
		AuditDAO auditDAO= new AuditDAO();
		logger.info("User Logged Out: "+user.getUsername());	
		Calendar sCal= Calendar.getInstance();
		auditDAO.insertAudit(new Audit(user.getUsername(),0,
				"LOGOUT",sCal.getTime(), sCal.getTime(),"LOGGED OUT: "+user.getUsername()));
	}
	public static void updateServerStatus(String cellName, String nodeName, String serverName, String status){
		ServerDAO serverDAO= new ServerDAO();
		serverDAO.updateServerStatus(cellName, nodeName, serverName,status);
	}
	public static void addAudit(Audit audit){
		AuditDAO auditDAO = new AuditDAO();
		auditDAO.insertAudit(audit);
	}

	
}
